<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue Chat Application</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        #app {
            width: 90%;
            max-width: 900px;
            background: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 10px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            height: 100%;
        }
        #login-container {
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background-color: #f8f8f8;
        }
        #login-container input {
            margin-bottom: 10px;
            padding: 10px;
            width: 80%;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        #login-container button {
            padding: 10px;
            width: 80%;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            font-size: 16px;
            cursor: pointer;
        }
        #chat-container {
            display: flex;
            flex: 1;
            overflow: hidden;
        }
        #friend-list {
            width: 220px;
            border-right: 1px solid #ccc;
            background-color: #f1f1f1;
            padding: 10px;
            overflow-y: auto;
        }
        #friend-list h3 {
            margin-top: 0;
            margin-bottom: 10px;
            font-size: 1.2em;
        }
        #friend-list div {
            padding: 12px;
            cursor: pointer;
            margin-bottom: 8px;
            border-radius: 5px;
            background-color: #e9e9e9;
            font-size: 1em;
        }
        #friend-list div:hover {
            background-color: #d8d8d8;
        }
        #friend-input-container {
            position: relative;
            margin-bottom: 15px;
        }
        #friend-input-container input {
            width: 100%;
            padding: 8px;
            padding-right: 50px; /* 为按钮预留空间 */
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 1em;
            box-sizing: border-box;
        }
        #friend-input-container button {
            position: absolute;
            right: 0;
            top: 0;
            height: 100%;
            padding: 8px 12px;
            border: none;
            border-radius: 0 5px 5px 0;
            background-color: #28a745;
            color: white;
            cursor: pointer;
            font-size: 1em;
        }
        #chat-box {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 10px;
            background-color: #fff;
            overflow-y: auto;
        }
        #chat-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        #chat-content {
            flex: 1;
            overflow-y: auto;
            padding-bottom: 10px;
            display: flex;
            flex-direction: column;
        }
        .message {
            display: inline-block;
            flex-direction: column;
            margin-bottom: 10px;
            max-width: 70%;
            min-width: 50px;
            border-radius: 10px;
            word-wrap: break-word;
            position: relative;
            padding: 10px 10px 20px 10px;
            vertical-align: top;
            font-size: 1em;
        }
        .message-username {
            font-weight: bold;
            margin-bottom: 5px;
            color: #555;
        }
        .message-content {
            font-size: 14px;
        }
        .message-info {
            font-size: 12px;
            color: #888;
            text-align: right;
            margin-top: 5px;
            position: absolute;
            right: 10px;
            bottom: 5px;
            line-height: 1;
        }
        .received-message {
            align-self: flex-start;
            background-color: #f1f1f1;
            color: #333;
        }
        .sent-message {
            align-self: flex-end;
            background-color: #afff78;
            color: white;
        }
        #message-input-container {
            display: flex;
            padding: 10px;
            background-color: #f8f8f8;
            border-top: 1px solid #ccc;
        }
        #message-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
        }
        #send-button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
</head>
<body>
<div id="app">
    <div v-if="!isLoggedIn" id="login-container">
        <h2>Login</h2>
        <input type="text" v-model="username" placeholder="Username">
        <input type="password" v-model="password" placeholder="Password">
        <button @click="login">Login</button>
    </div>
    <div v-else id="chat-container">
        <div id="friend-list">
            <h3>Friends</h3>
            <div id="friend-input-container">
                <input type="text" v-model="newFriendUsername" placeholder="Add friend by username">
                <button @click="addFriend">Add</button>
            </div>
            <div @click="subscribeToPublicChannel">
                Public Channel
            </div>
            <div v-for="friend in friends" :key="friend.username" @click="selectPrivateChat(friend.username)">
                {{ friend.username }}
            </div>
        </div>
        <div id="chat-box">
            <div id="chat-title">{{ chatTitle }}</div>
            <div id="chat-content">
                <div v-for="message in currentMessages" :key="message.timestamp" :class="['message', message.sender === username ? 'sent-message' : 'received-message']">
                    <!-- 公共频道显示用户名 -->
                    <div v-if="currentChannel === 'public'" class="message-username">
                        <strong>{{ message.sender }}</strong>
                    </div>
                    <div class="message-content">{{ message.content }}</div>
                    <div class="message-info">{{ formatTimestamp(message.timestamp) }}</div>
                </div>
            </div>
        </div>
    </div>
    <div v-if="isLoggedIn" id="message-input-container">
        <input type="text" v-model="messageInput" id="message-input" placeholder="Enter your message">
        <button @click="sendMessage" id="send-button">Send</button>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            username: '',
            password: '',
            isLoggedIn: false,
            friends: [],
            publicMessages: [],
            privateChats: {},  // 存储所有私聊消息的对象
            messageInput: '',
            newFriendUsername: '', // 用于添加好友的用户名输入
            socket: null,
            stompClient: null,
            currentRecipient: null,
            currentSubscription: {}, // 存储所有频道的订阅对象
            currentChannel: 'public' // 'public' or 'private'
        },
        computed: {
            currentMessages() {
                if (this.currentChannel === 'public') {
                    return this.publicMessages;
                } else if (this.currentRecipient && this.privateChats[this.currentRecipient]) {
                    return this.privateChats[this.currentRecipient];
                } else {
                    return [];
                }
            },
            chatTitle() {
                return this.currentChannel === 'public'
                    ? 'Public Channel'
                    : `Private Chat with ${this.currentRecipient}`;
            }
        },
        methods: {
            // 登录成功后建立WebSocket连接
            async login() {
                const response = await fetch('/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username: this.username, password: this.password })
                });
                alert(response.url)
                if (response.ok) {
                    const user = await response.json();
                    this.username = user.username;
                    this.isLoggedIn = true;
                    this.loadFriends();
                    this.connect(); // 登录成功后立即连接WebSocket
                } else {
                    alert('无效的账号或密码!');
                }
            },
            async addFriend() {
                if (this.newFriendUsername) {
                    try {
                        const response = await fetch('/auth/addFriend?username='+this.username+"&friendname="+this.newFriendUsername, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        if (response.ok) {
                            alert("Friend added successfully!");
                            this.loadFriends(); // 添加成功后重新加载好友列表
                            this.newFriendUsername = ''; // 清空输入框
                        } else {
                            alert("Failed to add friend.");
                        }
                    } catch (error) {
                        console.error("Error adding friend:", error);
                    }
                } else {
                    alert("Please enter a username.");
                }
            },
            connect() {
                this.socket = new SockJS('/ws');
                this.stompClient = Stomp.over(this.socket);

                this.stompClient.connect({}, () => {
                    console.log('WebSocket connected');
                    // 不在这里立即订阅频道，只是建立连接
                });

                this.stompClient.onclose = () => {
                    console.log('WebSocket closed');
                };

                this.stompClient.onerror = (error) => {
                    console.log('WebSocket error:', error);
                };
            },

            async loadFriends() {
                const response = await fetch(`/api/friends/${this.username}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                if (response.ok) {
                    this.friends = await response.json();
                }
            },

            sendSystemMessage(content) {
                const systemMessage = {
                    sender: 'System',
                    recipient: null,
                    content: `${this.username} ${content}`,
                    type: 'CHAT',
                    timestamp: new Date().getTime()
                };

                const destination = `/app/public-channel`;

                this.stompClient.send(destination, {}, JSON.stringify(systemMessage));
            },

            // 当用户点击公共频道时，建立公共频道的订阅
            subscribeToPublicChannel() {
                if (!this.currentSubscription.public) {
                    this.currentSubscription.public = this.stompClient.subscribe('/topic/public', (message) => {
                        const chatMessage = JSON.parse(message.body);
                        this.publicMessages.push(chatMessage);
                        this.scrollToBottom();
                    });
                    // 向公共频道发送加入消息
                    this.sendSystemMessage('has joined the public channel.');
                }

                this.currentChannel = 'public';
                this.currentRecipient = null;
            },

            // 当用户点击私人聊天时，建立相应的私人频道订阅
            selectPrivateChat(friendUsername) {
                if (this.currentRecipient === friendUsername && this.currentChannel === 'private') {
                    return;
                }

                // 当用户从公共频道切换到私人聊天时，发送离开公共频道的系统消息
                if (this.currentChannel === 'public') {
                    this.sendSystemMessage('has left the public channel.');
                }

                this.currentRecipient = friendUsername;
                this.currentChannel = 'private';

                if (!this.privateChats[friendUsername]) {
                    this.$set(this.privateChats, friendUsername, []);
                }

                if (!this.currentSubscription[friendUsername]) {
                    this.currentSubscription[friendUsername] = this.stompClient.subscribe(`/queue/private-${this.username}-${friendUsername}`, (message) => {
                        const chatMessage = JSON.parse(message.body);
                        this.privateChats[friendUsername].push(chatMessage);
                        this.scrollToBottom();
                    });
                }
            },

            sendPublicMessage() {
                const chatMessage = {
                    sender: this.username,
                    recipient: null,
                    content: this.messageInput,
                    type: 'CHAT',
                    timestamp: new Date().getTime()
                };

                const destination = `/app/public-channel`;

                this.stompClient.send(destination, {}, JSON.stringify(chatMessage));

                this.messageInput = '';
            },

            sendPrivateMessage() {
                const chatMessage = {
                    sender: this.username,
                    recipient: this.currentRecipient,
                    content: this.messageInput,
                    type: 'CHAT',
                    timestamp: new Date().getTime()
                };

                const destination = `/app/private-channel`;

                this.stompClient.send(destination, {}, JSON.stringify(chatMessage));
                this.privateChats[this.currentRecipient].push(chatMessage);
                this.scrollToBottom();

                this.messageInput = '';
            },

            sendMessage() {
                if (this.currentChannel === 'public') {
                    this.sendPublicMessage();
                } else {
                    this.sendPrivateMessage();
                }
            },

            scrollToBottom() {
                this.$nextTick(() => {
                    const chatContent = this.$el.querySelector("#chat-content");
                    chatContent.scrollTop = chatContent.scrollHeight;
                });
            },

            formatTimestamp(timestamp) {
                const date = new Date(timestamp);
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                return `${hours}:${minutes}`;
            }
        }

    });
</script>
</body>
</html>
